const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
  })
const db = cloud.database({
    throwOnNotFound: false
})
const _ = db.command;
const globalConfig = require('../../config/index')
const $ = db.command.aggregate

module.exports =async (event,context,root)=>{
    const {
        OPENID,UNIONID
    } = cloud.getWXContext();
    let parame = event.data||{};
    try {
        var result = null;

		if( parame.avatarUrl ){
			result = await db.collection('user_info').where({
				openId: _.eq(OPENID)
			}).update({
				data:{
					avatarUrl: parame.avatarUrl 
				}
			})
		}
		if( parame.nickName ){
			result = await db.collection('user_info').where({
				openId: _.eq(OPENID)
			}).update({
				data:{
					nickName: parame.nickName 
				}
			})
		}
		
		result = await db.collection('user_info').where({ openId: _.eq(OPENID) }).get();
		try {
			result = result.data[0]||{}
		} catch (error) {
			result = {}
		}

        var res = {
            errcode:200,
            msg: "操作成功!",
            result:result,
            success:true,
            timestamp:new Date().getTime()
        }
    } catch (error) {
        var error_type = globalConfig.common.error_type(error.errCode);
        var res = {
             errcode:404,
             msg: error_type.type,
             result:error,
             success:false,
             timestamp:new Date().getTime()
        }
    }
    return res;
}